<template>
  <div class="admin-categories">
    <div class="header-section">
      <h2>分类管理</h2>
      <p>管理商品分类，支持多级分类结构</p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-card>
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </el-card>
    </div>

    <!-- 分类树展示 -->
    <div class="tree-section">
      <el-card>
        <template #header>
          <span>分类树结构</span>
        </template>
        
        <el-tree
          :data="categoryTree"
          :props="treeProps"
          node-key="categoryId"
          default-expand-all
          v-loading="loading"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <span class="node-label">{{ data.name }}</span>
              <div class="node-info">
                <el-tag size="small" :type="data.isLeaf === 1 ? 'info' : 'success'">
                  {{ data.isLeaf === 1 ? '叶子节点' : '父节点' }}
                </el-tag>
                <el-tag size="small" type="warning">层级: {{ data.level }}</el-tag>
              </div>
              <div class="node-actions">
                <el-button size="small" type="primary" @click.stop="showEditDialog(data)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  @click.stop="showAddChildDialog(data)"
                  v-if="data.isLeaf === 1"
                >
                  <el-icon><Plus /></el-icon>添加子分类
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click.stop="handleDelete(data)"
                  v-if="data.isLeaf === 1"
                >
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 添加分类对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加分类"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-select v-model="addForm.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option label="根分类" :value="0" />
            <el-option
              v-for="category in parentCategories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd" :loading="addLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑分类"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-select v-model="editForm.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option label="根分类" :value="0" />
            <el-option
              v-for="category in parentCategories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
              :disabled="category.categoryId === editForm.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit" :loading="editLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const categoryTree = ref([])
const parentCategories = ref([])

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const addLoading = ref(false)
const editLoading = ref(false)

// 表单引用
const addFormRef = ref()
const editFormRef = ref()

// 添加表单
const addForm = reactive({
  name: '',
  parentId: 0
})

// 编辑表单
const editForm = reactive({
  categoryId: null,
  name: '',
  parentId: 0
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择父分类', trigger: 'change' }
  ]
}

// 获取分类树
const fetchCategoryTree = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/admin/categories')
    if (response.success) {
      categoryTree.value = response.data || []
    } else {
      ElMessage.error('获取分类树失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取分类树失败:', error)
    ElMessage.error('获取分类树失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取父分类选项
const fetchParentCategories = async () => {
  try {
    const response = await request.get('/api/admin/categories/parents')
    if (response.success) {
      parentCategories.value = response.data || []
    }
  } catch (error) {
    console.error('获取父分类失败:', error)
  }
}

// 显示添加对话框
const showAddDialog = () => {
  addForm.name = ''
  addForm.parentId = 0
  addDialogVisible.value = true
}

// 显示添加子分类对话框
const showAddChildDialog = (parentCategory) => {
  addForm.name = ''
  addForm.parentId = parentCategory.categoryId
  addDialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (category) => {
  editForm.categoryId = category.categoryId
  editForm.name = category.name
  editForm.parentId = category.parentId
  editDialogVisible.value = true
}

// 处理添加
const handleAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    const response = await request.post('/api/admin/categories', addForm)
    if (response.success) {
      ElMessage.success('添加分类成功')
      addDialogVisible.value = false
      fetchCategoryTree()
      fetchParentCategories()
    } else {
      ElMessage.error('添加分类失败: ' + response.message)
    }
  } catch (error) {
    console.error('添加分类失败:', error)
    ElMessage.error('添加分类失败: ' + error.message)
  } finally {
    addLoading.value = false
  }
}

// 处理编辑
const handleEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    const response = await request.put(`/api/admin/categories/${editForm.categoryId}`, editForm)
    if (response.success) {
      ElMessage.success('更新分类成功')
      editDialogVisible.value = false
      fetchCategoryTree()
      fetchParentCategories()
    } else {
      ElMessage.error('更新分类失败: ' + response.message)
    }
  } catch (error) {
    console.error('更新分类失败:', error)
    ElMessage.error('更新分类失败: ' + error.message)
  } finally {
    editLoading.value = false
  }
}

// 处理删除
const handleDelete = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(`/api/admin/categories/${category.categoryId}`)
    if (response.success) {
      ElMessage.success('删除分类成功')
      fetchCategoryTree()
      fetchParentCategories()
    } else {
      ElMessage.error('删除分类失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败: ' + error.message)
    }
  }
}

// 刷新数据
const refreshData = () => {
  fetchCategoryTree()
  fetchParentCategories()
}

// 初始化
onMounted(() => {
  fetchCategoryTree()
  fetchParentCategories()
})
</script>

<style scoped>
.admin-categories {
  padding: 20px;
}

.header-section {
  margin-bottom: 20px;
}

.header-section h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.header-section p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.action-section {
  margin-bottom: 20px;
}

.tree-section {
  margin-bottom: 20px;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 8px 0;
}

.node-label {
  font-weight: 500;
  color: #303133;
  flex: 1;
}

.node-info {
  display: flex;
  gap: 8px;
  margin: 0 16px;
}

.node-actions {
  display: flex;
  gap: 8px;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 4px 0;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

:deep(.el-tree-node__expand-icon) {
  margin-right: 8px;
}
</style> 